<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>首页轮播图管理</span>
        <el-button style="float:right" v-hasPermi="['admin:homepage:image:list']" type="primary" size="small" @click="fetchList">查询</el-button>
        <el-button style="float:right" v-hasPermi="['admin:homepage:image:insert']" type="primary" size="small" @click="openAdd">新增</el-button>
      </div>

      <el-row>
        <el-col :span="24">
          <el-table :data="list" stripe style="width:100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="图片" min-width="160">
              <template slot-scope="scope">
                <img v-if="scope.row.imageUrl" :src="'https://www.r8club.cn/Apipc/crmebimage/' + scope.row.imageUrl" style="height:60px;" />
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="140" />
            <el-table-column prop="createTime" label="创建时间" min-width="180" />
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-hasPermi="['admin:homepage:image:update']" @click="onEdit(scope.row)">修改</el-button>
                <el-button type="text" size="small" v-hasPermi="['admin:homepage:image:delete']" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <div style="margin-top:16px; text-align:right">
        <el-button type="primary" size="small" @click="fetchList">刷新</el-button>
      </div>
    </el-card>

    <el-dialog title="新增轮播图" :visible.sync="dialogVisible">
      <el-form :model="form" label-width="80px">
        <el-form-item label="图片" prop="imageUrl">
          <div style="display:flex; align-items:center">
            <el-button size="small" @click="openUploader">选择图片/上传</el-button>
            <div style="margin-left:12px">
              <img v-if="form.imageUrl" :src="getImageSrc(form.imageUrl)" style="height:60px" />
              <span v-else style="color:#999">未选择图片</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="form.type" placeholder="例如：banner" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 图片选择器弹窗 -->
    <el-dialog title="选择图片" :visible.sync="uploaderVisible" width="80%">
      <!-- 传空 pictureType 以显示组件内的“使用选中图片”按钮 -->
      <upload-index :pictureType="''" :isMore="'0'" @getImage="onGetImage"></upload-index>
    </el-dialog>
  </div>
</template>

<script>
import { listHomepageImage, insertHomepageImage, updateHomepageImage, deleteHomepageImage } from '@/api/homepageImage'
import UploadIndex from '@/components/uploadPicture/index.vue'

export default {
  name: 'Branner',
  data() {
    return {
      list: [],
      loading: false,
      dialogVisible: false,
  uploaderVisible: false,
      // 查询参数，若无值则传空字符串
      query: {
        createBy: '',
        createTime: '',
        id: '',
        imageUrl: '',
        type: '',
        updateBy: '',
        updateTime: ''
      },
      form: {
        imageUrl: '',
        type: ''
      }
    }
  },
  components: { UploadIndex },
  created() {
    this.fetchList()
  },
  methods: {
    fetchList() {
      this.loading = true
      const params = {
        type: '',
      }
      listHomepageImage(params).then(res => {
        // 根据后端返回结构可能为 { code, data, message }
        if (res && res.data) {
          this.list = res.data
        } else if (Array.isArray(res)) {
          this.list = res
        } else if (res && res.length) {
          this.list = res
        } else {
          this.list = []
        }
      }).catch(() => {
        this.$message.error('获取列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    openAdd() {
      this.form = { imageUrl: '', type: '' }
      this.dialogVisible = true
    },
    // 打开图片选择器对话框
    openUploader() {
      this.uploaderVisible = true
    },
    // 添加一个方法来判断图片URL是否已经是完整的链接，如果不是则拼接域名
    getImageSrc(imageUrl) {
      // 判断是否已经是完整的URL（以http或https开头）
      if (imageUrl && (imageUrl.startsWith('http://') || imageUrl.startsWith('https://'))) {
        return imageUrl;
      } else {
        return 'https://www.r8club.cn/Apipc/crmebimage/' + imageUrl;
      }
    },
    
    // 处理从 UploadIndex 选择/上传回来的图片
    onGetImage(images) {
      // 打印调试信息，查看组件回传了什么
      console.log('onGetImage payload:', images)
      // 如果 payload 是数组并且第一项带有 sattDir，直接使用它（优先处理）
      if (Array.isArray(images) && images.length && images[0] && images[0].sattDir) {
        this.form.imageUrl = images[0].sattDir
        console.log('direct sattDir assign:', this.form.imageUrl)
        this.uploaderVisible = false
        this.$nextTick(() => console.log('form.imageUrl after set:', this.form.imageUrl))
        return
      }
      let url = ''
      if (!images) {
        url = ''
      } else if (typeof images === 'string') {
        url = images
      } else if (Array.isArray(images) && images.length) {
        const img = images[0]
        if (typeof img === 'string') {
          url = img
        } else if (img && typeof img === 'object') {
          url = img.sattDir || img.sattDir || img.imageUrl || img.url || img.path || img.attDir || img.satt_dir || ''
        }
      } else if (typeof images === 'object') {
        const img = images
        url = img.sattDir || img.imageUrl || img.url || img.path || img.attDir || img.satt_dir || ''
      }

      if (url) {
        console.log('resolved url:', url)
        this.form.imageUrl = url
        this.$nextTick(() => console.log('form.imageUrl after set:', this.form.imageUrl))
      } else {
        // 没有拿到地址，提示并在控制台保留信息供调试
        this.$message.info('未获取到图片地址，请在图片选择器中点击“使用选中图片”或检查返回值')
        console.warn('onGetImage did not resolve an URL. payload:', images)
      }
      this.uploaderVisible = false
    },
    submitAdd() {
      if (!this.form.imageUrl) {
        this.$message.warn('图片地址不能为空')
        return
      }
      // 如果 imageUrl 包含指定前缀 https://www.r8club.cn/Apipc/crmebimage/，去掉它后再提交
      const prefixRegex = /^https?:\/\/www\.r8club\.cn\/Apipc\/crmebimage\//i
      if (this.form.imageUrl) {
        this.form.imageUrl = this.form.imageUrl.replace(prefixRegex, '')
      }
      // 若存在 id，则为编辑，调用更新接口
      if (this.form.id) {
        updateHomepageImage(this.form).then(res => {
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.fetchList()
        }).catch(() => {
          this.$message.error('更新失败')
        })
      } else {
        insertHomepageImage(this.form).then(res => {
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.fetchList()
        }).catch(() => {
          this.$message.error('新增失败')
        })
      }
    },
    // 编辑：填充表单并打开弹窗
    onEdit(row) {
      this.form = { id: row.id, imageUrl: row.imageUrl, type: row.type }
      this.dialogVisible = true
    },
    // 删除：确认后调用删除接口
    onDelete(row) {
      this.$modalSure('确认删除该配置？').then(() => {
        deleteHomepageImage(row.id).then(() => {
          this.$message.success('删除成功')
          this.fetchList()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    },
    preview(row) {
      if (row && row.imageUrl) {
        window.open(row.imageUrl)
      } else {
        this.$message.info('无图片可预览')
      }
    }
  }
}
</script>

<style scoped>
.divBox { padding: 12px }
</style>